package org.easy4j.framework.core.datasource.support;

import com.alibaba.druid.pool.DruidDataSource;
import org.easy4j.framework.core.config.Config;
import org.easy4j.framework.core.config.DataSourceConfig;
import org.easy4j.framework.core.datasource.DataSourceFactory;
import org.easy4j.framework.core.orm.DbAccessException;
import org.springframework.util.ClassUtils;

import javax.sql.DataSource;
import java.sql.SQLException;


/**
 * @author bjliuyong
 * @version 1.0
 * @created date 16-3-16
 */
public class DefaultDataSourceFactory implements DataSourceFactory {


    /**
     * Get the {@link javax.sql.DataSource}
     */
    @Override
    public DataSource getDataSource() {

        if(!ClassUtils.isPresent("com.alibaba.druid.pool.DruidDataSource" ,
                ClassUtils.getDefaultClassLoader()))
            return null ;

        return initDruidDataSource();
    }

    private DataSource initDruidDataSource(){

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(         Config.getValue(DataSourceConfig.JDBC_URL)       );
        druidDataSource.setUsername(    Config.getValue(DataSourceConfig.JDBC_USERNAME)  );
        druidDataSource.setPassword(    Config.getValue(DataSourceConfig.JDBC_PASSWORD)  );
        druidDataSource.setMaxActive(   Config.getInt(  DataSourceConfig.MAX_ACTIVE , 5) );

        druidDataSource.setTestWhileIdle(true);
        druidDataSource.setValidationQuery("SELECT 'x'");

        try {
            druidDataSource.init();
        } catch (SQLException e) {
            throw new DbAccessException(e);
        }

        return druidDataSource;
    }
}
